﻿namespace LiJ.Common.Extention.Volidate
{
    /// <summary>
    /// 数字验证属性
    /// </summary>
    public class LNumberAttribute : BaseValidateAttribute
    {
        /// <summary>
        /// 最小值
        /// </summary>
        private readonly long min;

        /// <summary>
        /// 最大值
        /// </summary>
        private readonly long max;

        public LNumberAttribute(long _min = -9223372036854775808L, long _max = 9223372036854775807L,
            string _errorMessage = null)
        {
            this.min = _min;
            this.max = _max;
            this.errorMessage = _errorMessage;
        }

        /// <summary>
        /// 数字验证方法
        /// </summary>
        /// <param name="propertyName">属性名称</param>
        /// <param name="propertyValue">属性值</param>
        /// <returns><c>true</c><value>校验正确</value><c>false</c><value>校验失败</value></returns>
        internal override bool Validate(string propertyName, object propertyValue)
        {
            if (propertyValue == null)
            {
                base.errorMessage = (base.errorMessage ?? $"{propertyName}的值不能为空！");
                return false;
            }

            var flag = false;
            if (long.TryParse(propertyValue.ToString(), out long num))
            {
                flag = (this.min <= num && this.max >= num);
                base.errorMessage =
                    (flag ? string.Empty : (base.errorMessage ?? $"{propertyName}的值必须介于{this.min}~{this.max}的数值！"));
            }
            else
            {
                base.errorMessage = (base.errorMessage ?? $"{propertyName}的值必须是数字类型！");
            }

            return flag;
        }
    }
}